package org.watchrecords.pages.user;

import java.util.Arrays;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.watchrecords.annotations.InstantiationPermission;
import org.watchrecords.constants.Permission;
import org.watchrecords.constants.Role;
import org.watchrecords.dbo.User;
import org.watchrecords.elements.BasicForm;
import org.watchrecords.managers.UserManager;
import org.watchrecords.pages.BasicPage;

import com.google.inject.Inject;

@InstantiationPermission(Permission.EDIT_USER)
public class EditUserPage extends BasicPage {
    @Inject private UserManager userManager;

    public EditUserPage(PageParameters pageParameters) {
        super(pageParameters);
        Integer userId = getPageParameters() == null ? null : getPageParameters().getAsInteger("userId");
        User user = userId == null ? new User() : userManager.getUser(userId);
        FeedbackPanel feedbackPanel = new FeedbackPanel("feedbackPanel");
        
        add(new Label("header", userId == null ? "Add User": "Edit User: " + user.getName()));
        add(new EditUserForm("form", user));
        add(feedbackPanel);
    }
    
    class EditUserForm extends BasicForm<User> {
        @Override
        protected void doSubmit() {
            User user = this.getModelObject();
            userManager.saveUser(user);
            setResponsePage(UserListPage.class);
        }

        /**
         * 
         */
        private static final long serialVersionUID = -8879410840840703135L;

        public EditUserForm(String id, User user) {
            super(id, user);
            
            user.setOriginalPassword(user.getPassword());
            
            add(new TextField<String>("name").setEnabled(user.getId() == null));
            add(new PasswordTextField("password"));
            add(new PasswordTextField("confirmPassword").setRequired(false));
            add(new TextField<String>("email"));
            add(new TextField<String>("characterName").setRequired(false));
            add(new TextField<Integer>("argentNode").setRequired(false));
            add(new DropDownChoice<Role>("role", Arrays.asList(Role.values())));
            add(new Button("cancel") {
                private static final long serialVersionUID = -7204043210850354787L;

                @Override
                public void onSubmit() {
                    setResponsePage(UserListPage.class);
                }
            }.setDefaultFormProcessing(false));
        }
        
    }
}
